package client.ui.theme.defaultTheme;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.JTextArea;

import client.engine.ChatEngine;
import client.engine.ChatRoom;
import client.ui.IChatRoomTab;
import client.ui.IChatRoomWindow;

public class DefaultChatRoomTab extends javax.swing.JPanel implements IChatRoomTab {

	private ChatRoom chatRoom = null;
	private ChatEngine engine = null;
	private IChatRoomWindow window = null;
	
	//private javax.swing.JScrollPane messageScrollPane;
    //private javax.swing.JScrollPane participantScrollPane;
    
    
    private javax.swing.JButton inviteBuddyButton;
    private javax.swing.JButton closeTabButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane messageScrollPane;
    private javax.swing.JScrollPane participantsScrollPane;
    private javax.swing.JTextArea messageTextArea;
    private javax.swing.JList participantList;
    private javax.swing.JButton sendButton;
    private javax.swing.JTextField sendField;
    private javax.swing.JButton sendFileButton;
	
	public DefaultChatRoomTab() {
		initComponents();
		messageTextArea.setText("You sense a disturbance in the Force...\n\n");
	}
	
	@Override
	public void closeTab() {
		
		window.removeTab(this);
		chatRoom.closeConversation();
		
	}

	@Override
	public void setChatEngine(ChatEngine engine) {

		this.engine = engine;

	}

	@Override
	public void setChatRoom(ChatRoom room) {
		
		this.chatRoom = room;
		updateParticipants(chatRoom.getParticipants());

	}

	@Override
	public void showMessage(String message, String sender) {
		
		messageTextArea.append(sender + ": " + message + "\n");
		messageTextArea.setCaretPosition( messageTextArea.getDocument().getLength() );
		
	}

	@Override
	public void updateParticipants(ArrayList<String> participants) {

		String[] names = new String[participants.size()];
		participants.toArray(names);
		final String[] content = names;
		participantList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = content;
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });

	}
	
	    private void initComponents() {

	    	 messageScrollPane = new javax.swing.JScrollPane();
	         messageTextArea = new javax.swing.JTextArea();
	         participantsScrollPane = new javax.swing.JScrollPane();
	         participantList = new javax.swing.JList();
	         sendField = new javax.swing.JTextField();
	         sendButton = new javax.swing.JButton();
	         sendFileButton = new javax.swing.JButton();
	         inviteBuddyButton = new javax.swing.JButton();
	         jLabel1 = new javax.swing.JLabel();
	         closeTabButton = new javax.swing.JButton();

	         messageTextArea.setColumns(20);
	         messageTextArea.setRows(5);
	         messageTextArea.setLineWrap(true);
	         messageTextArea.setWrapStyleWord(true);
	         messageTextArea.setAutoscrolls(true);
	         messageTextArea.setEditable(false);
	         messageScrollPane.setViewportView(messageTextArea);
	         

	         participantsScrollPane.setViewportView(participantList);

	         sendButton.setText("Send");
	         sendButton.addActionListener(new java.awt.event.ActionListener() {
	             public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	 sendButtonActionPerformed(evt);
	             }
	         });
	         
	         sendFileButton.setText("Send File");
	         sendFileButton.addActionListener(new java.awt.event.ActionListener() {
	        	 public void actionPerformed(java.awt.event.ActionEvent evt) {
	                 sendFileButtonActionPerformed(evt);
	             }
	         });

	         inviteBuddyButton.setText("Invite Buddy");
	         inviteBuddyButton.addActionListener(new java.awt.event.ActionListener() {
	             public void actionPerformed(java.awt.event.ActionEvent evt) {
	                 inviteBuddyButtonActionPerformed(evt);
	             }
	         });

	         jLabel1.setText("Participants");

	         closeTabButton.setText("Close Tab");
	         closeTabButton.addActionListener(new java.awt.event.ActionListener() {
	             public void actionPerformed(java.awt.event.ActionEvent evt) {
	                 closeTabButtonActionPerformed(evt);
	             }
	         });

	         sendField.addKeyListener(new KeyListener(){
				@Override
				public void keyPressed(KeyEvent arg0) {
					DefaultChatRoomTab.this.keyPressed(arg0);
				}

				@Override
				public void keyReleased(KeyEvent arg0) {
					
				}

				@Override
				public void keyTyped(KeyEvent arg0) {
					
				}
	         });
	         
	         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
	         this.setLayout(layout);
	         layout.setHorizontalGroup(
	             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	             .addGroup(layout.createSequentialGroup()
	                 .addContainerGap()
	                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                     .addGroup(layout.createSequentialGroup()
	                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                             .addComponent(messageScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
	                             .addComponent(sendFileButton))
	                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
	                             .addGroup(layout.createSequentialGroup()
	                                 .addGap(3, 3, 3)
	                                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                                     .addGroup(layout.createSequentialGroup()
	                                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                                         .addComponent(participantsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE))
	                                     .addGroup(layout.createSequentialGroup()
	                                         .addGap(30, 30, 30)
	                                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                                             .addComponent(closeTabButton)
	                                             .addComponent(jLabel1))
	                                         .addGap(8, 8, 8))))
	                             .addGroup(layout.createSequentialGroup()
	                                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                                 .addComponent(inviteBuddyButton)))
	                         .addContainerGap())
	                     .addGroup(layout.createSequentialGroup()
	                         .addComponent(sendField, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
	                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                         .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
	                         .addGap(9, 9, 9))))
	         );
	         layout.setVerticalGroup(
	             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	             .addGroup(layout.createSequentialGroup()
	                 .addContainerGap()
	                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
	                         .addComponent(closeTabButton)
	                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
	                         .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
	                         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                         .addComponent(participantsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))
	                     .addComponent(messageScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE))
	                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                     .addComponent(sendFileButton)
	                     .addComponent(inviteBuddyButton))
	                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                     .addComponent(sendField, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
	                     .addComponent(sendButton))
	                 .addContainerGap())
	         );
	    }

	    private void sendButtonActionPerformed(ActionEvent evt) {
			
	    	String message = this.sendField.getText();
	    	this.engine.sendMessage(chatRoom.getID(), message);
			System.out.println(message);
			sendField.setText("");
	    	
		}

		@Override
		public void setChatRoomWindow(IChatRoomWindow window) {
			
			this.window = window;
			
		}
		
	  private void inviteBuddyButtonActionPerformed(java.awt.event.ActionEvent evt) {

		  DefaultInviteWindow w = new DefaultInviteWindow(this, engine.getBuddyList());
		  w.setVisible(true);
		  
	  }

	  public void invite(String name){
		  
		  chatRoom.inviteBuddy(name);
		  
	  }
	  
	  private void sendFileButtonActionPerformed(ActionEvent evt) {
		  
		  JFileChooser fileChooser = new JFileChooser();
		  
		  int result = fileChooser.showOpenDialog(this);
		  
		  if(result == JFileChooser.APPROVE_OPTION){
			  File f = fileChooser.getSelectedFile();

			  if(f != null){
				  String receiver = null;
				  ArrayList<String> participants = chatRoom.getParticipants();
				  for(int i = 0; i < participants.size(); i++){
					  String rec = participants.get(i);
					  if(!rec.equals(engine.getUsername())){
						  receiver = rec;
						  break;
					  }
				  }
				  if(receiver != null){
					  System.out.println("Sending file " + f.getName() + " to " + receiver);
					  engine.sendFile(receiver, f.getPath(), f.getName());
				  }
			  }
		  }
			
	  }
	  
	  private void closeTabButtonActionPerformed(ActionEvent evt) {
		  
		  this.closeTab();
		  
	  }
	  
	  private void sendButtonActionPerformed() {
			
	    	String message = this.sendField.getText();
	    	if(!message.equals("")){
	    		this.engine.sendMessage(chatRoom.getID(), message);
	    		sendField.setText("");
	    	}
	    	messageTextArea.setCaretPosition( messageTextArea.getDocument().getLength() );
			
	  }
		    
	public void keyPressed(KeyEvent e) {
	    int key = e.getKeyCode();
	    if (key == KeyEvent.VK_ENTER) {
	       sendButtonActionPerformed();
	    }
	}

	public JTextArea getMessageTextArea()
	{
		return messageTextArea;
	}
}
